import tools from '@/utils/tools'
import {ElMessageBox} from 'element-plus'
import store from '@/store'
import i18n from "@/utils/i18n";
import router from "@/router";
import {isAuthenticated} from "@/utils/common";
import api from "@/api";
import $axios from "@/utils/axios";

// 清除用户登录状态
function clearCurrentUser() {
    tools.removeSessionItem('CurrentUserName')
    tools.removeSessionItem('selectedAgency')
    tools.removeLocalItem('defaultCenterId')
    tools.deletCookie('CurrentUserName')
    tools.removeSessionItem('CurrentUserPassword')
    tools.deletCookie('CurrentUserPassword')
    tools.deletCookie('currentUser')
    tools.deletCookie('currentAgencies')
    tools.deletCookie('timestamp')
}

// 清楚导入缓存
function clearImportInfo() {
    tools.removeSessionItem('ImportData')
    tools.removeSessionItem('ImportIndex')
    tools.removeSessionItem('ImportName')
    tools.removeSessionItem('ImportSuccessData')
    tools.removeSessionItem('ImportSkipData')
    tools.removeLocalItem('mergeSuccessSign')
}

// 退出
export const toSignOut = () => {
    $axios.post(api.urls().logout)
        .then(response => {
        }).catch(error => {
    }).finally(
            () => {
                tools.sessionItem('USER_SIGN_OUT', true)
                clearImportInfo()
                clearCurrentUser()
                // 跳转登录界面
                router.push({name: 'login'})
                store.dispatch('setCurrentUserAction', null)
                // 关闭所有弹出层，初始化自动退出变量
                ElMessageBox.close()
                init()
            }
        )
}
// 重置自动退出时间
export const resetTimeout = () => {
    if (!assertRefresh()) {
        setCacheTime()
        return
    }
    assertUserTimeout()
    setCacheTime()
}

// 获取当前时间
function getCurrentTime() {
    return new Date().getTime()
}

// 设置当前隐藏时间
function setCacheTime() {
    var timestamp = new Date().getTime()
    tools.setCookie('timestamp', timestamp)
}

// 获取当前隐藏时间
function getCacheTime() {
    return tools.getCookie('timestamp')
}

// 判断是否登录、是否记住密码登录、是否弹窗提示剩余时间
function assertRefresh() {
    if (!isAuthenticated()) {
        return false
    }
    if (isAlertWarnInfo) {
        return false
    }
    return true
}

function handleViewByJudgeTime() {
    if (!assertRefresh()) {
        assertUserTimeout()
        return
    }
    cacheTime = getCacheTime()
    currentTime = getCurrentTime()
    if (cacheTime) {
        cacheTime = parseInt(cacheTime)
        if ((warnTimerNum + cacheTime) <= currentTime && (warnTimerNum + cacheTime + toSignOutNum) > currentTime) {
            signOutTimer = setTimeout(toSignOut, toSignOutNum)
            isAlertWarnInfo = true
            ElMessageBox.alert(i18n.global.t('loc.plsSaveEdit'), i18n.global.t('loc.confirmation'), {
                confirmButtonText: i18n.global.t('loc.ok'),
                type: 'warning',
                customClass: 'lg-modal-warning'
            }).then(() => {
                isAlertWarnInfo = false
                assertUserTimeout()
            })
        } else if ((warnTimerNum + cacheTime + toSignOutNum) <= currentTime) {
            toSignOut()
        } else {
            assertUserTimeout()
        }
    } else {
        setCacheTime()
        assertUserTimeout()
    }
}

function assertUserTimeout() {
    if (timer) {
        clearTimeout(timer)
    }
    if (signOutTimer) {
        clearTimeout(signOutTimer)
    }
    timer = setTimeout(handleViewByJudgeTime, 1000 * 60 * 2)
}

// 用户操作时触发重新设置当前隐藏时间
function operateHandler() {
    if (!assertRefresh()) {
        setCacheTime()
        return
    }
    assertUserTimeout()
    setCacheTime()
}

document.onkeydown = (event) => {
    operateHandler()

}
document.onmousedown = (event) => {
    operateHandler()
}

let timer = null // 时间戳
let signOutTimer = null // 退出时间
let warnTimerNum = 1000 * 60 * 25 // 提醒时间
let toSignOutNum = 1000 * 60 * 5 // 自动退出时间
let isAlertWarnInfo = false // 警告是否弹出
let cacheTime, currentTime // 隐藏时间，当前时间

function init() {
    timer = null // 时间戳
    signOutTimer = null // 退出时间
    isAlertWarnInfo = false // 警告是否弹出

    cacheTime = getCacheTime()
    currentTime = getCurrentTime()

    if (cacheTime) {
        cacheTime = parseInt(cacheTime)
        if ((warnTimerNum + cacheTime + toSignOutNum) <= currentTime && assertRefresh()) {
            toSignOut()
        } else {
            assertUserTimeout()
        }
    } else {
        setCacheTime()
        assertUserTimeout()
    }
    // 如果ipad，设置定时器，每分钟刷新一次自动退出时间
    if (tools.isComeFromIPad()) {
        setInterval(() => {
            resetTimeout()
        }, 1000 * 60 * 1)
    }
}

init()
